<?php
defined('BASEPATH') OR exit('No direct script access allowed');
/**
 * 商品类别 控制层
 * @author adela.xu 8.29
 */
class Category extends My_Controller
{
    private $assign = array();
    /**
     * 默认方法
     * @author Toby.tu 2016-09-01
     */
    public function init(){
        $this->vendor('models/Category_model','category_model');
        $this->assign['module'] = 'category';
        $this->assign['is_admin'] = $this->permis_logic->isAdmin();
    }
    /**
     * 用户列表
     * @author Toby.tu 2016-08-30
     */
    public function index(){
        $input = $this->input->post();
        $cur_page = 1;
        if(isset($input['cur_page'])){
            $cur_page = $input['cur_page'];
        }
        $search = array();
        $filter = array(
            'name','status'
        );
        foreach ($filter as $fld) {
            if(isset($input[$fld]) && trim($input[$fld]) != ''){
                $search[$fld] = $input[$fld];
            }
        }
        $brand_id = 0;
        if(isset($input['brand_id']) && $input['brand_id'] > 0){
            $brand_id = $input['brand_id'];
        }else if('yes' != $this->assign['is_admin']){//非管理员
            $brand_id = $this->permis_logic->getLoginUserInfo()['brand_id'];
            if(empty($brand_id)){
                die('没有品牌权限。');
            }
        }
        if($brand_id > 0) $search['brand_id'] = $brand_id;
        $search['is_admin'] = $this->assign['is_admin'];//是否管理员
        $this->pagesize = 2;
        if($brand_id > 0){
            $categorys = $this->category_model->getcategoryList($search,$cur_page,$this->pagesize);
        }else{
            $categorys = array();
        }
        $this->assign['search'] = $search;
        $this->assign['categoryList'] = $this->common->sortLevelArray($categorys);
        //获取品牌列表
        if('yes' == $this->assign['is_admin']){
            $this->vendor('@.Brand_model');
            $brands = $this->brand_model->getAll();
            $this->assign['brand_opts'] = $brands;
        }
        if(isset($input['ajax']) && 1 == $input['ajax']){
            $this->load->view('admin/category/list',$this->assign);
        }else{
            $this->assign['view'] = 'admin/category/index';
            $this->load->view('admin/common/frame',$this->assign);
        }
    }
    /**
     * 创建页面
     * @author Toby.tu 2016-08-31
     */
    public function create($id=0){
        //获取品牌列表
        if('yes' == $this->assign['is_admin']){
            $this->vendor('@.Brand_model');
            $brands = $this->brand_model->getAll();
            $this->assign['brand_opts'] = $brands;
        }
        if($id > 0){
            $info = $this->category_model->getOne(['id'=>$id]);
            $this->assign['parent_id'] = $id;
            $this->assign['parent_name'] = $info['name'];
            $this->assign['level'] = $info['level']+1;
            $this->assign['brand_id'] = $info['brand_id'];
        }else{
            $this->assign['parent_id'] = 0;
            $this->assign['parent_name'] = '';
            $this->assign['level'] = 1;
        }
        $this->assign['view'] = 'admin/category/create';
        $this->load->view('admin/common/frame',$this->assign);
    }
    /**
     * 新增权限组
     * @author Toby.tu 2016-08-31
     */
    public function store(){
        try {
            $input = $this->input->post();
            if(!isset($input['category'])){
                throw new Exception('参数不正确。');
            }
            if(empty($input['category']['name'])){
                throw new Exception('请输入分类名称。');
            }
            $brand_id = 0;
            if(isset($input['category']['brand_id']) && $input['category']['brand_id'] > 0){
                $brand_id = $input['category']['brand_id'];
            }else if('yes' != $this->assign['is_admin']){//非管理员
                $brand_id = $this->permis_logic->getLoginUserInfo()['brand_id'];
            }
            if(empty($brand_id)){
                throw new Exception('没有对应的品牌，不能保存。');
            }
            $where = ['name'=>$input['category']['name']];
            $where['brand_id'] = $brand_id;
			$where['delete_id'] = 0;
            $category = $this->category_model->getOne($where);
            if(!empty($category)){
                throw new Exception('分类名称已存在。');
            }
            $param = array();
            $param['name'] = $input['category']['name'];
            // $param['upload_path'] = $input['category']['upload_path'];
            // $param['upload_file'] = $input['category']['upload_file'];
            // $param['upload_name'] = $input['category']['upload_name'];
            // $param['upload_type'] = $input['category']['upload_type'];
            // $param['upload_size'] = $input['category']['upload_size'];
            $param['imageurl'] = $input['category']['upload_url'];
            $param['create_time'] = $this->phpdate->time();
            $param['update_time'] = $param['create_time'];
            $param['create_id'] = $this->permis_logic->getLoginUserInfo()['id'];
            $param['update_id'] = $this->permis_logic->getLoginUserInfo()['id'];
            $param['brand_id'] = $brand_id;
            if(isset($input['category']['level'])){
                $param['level'] = $input['category']['level'];
            }
            if(isset($input['category']['parent_id']) && $input['category']['parent_id'] > 0){
                $param['parent_id'] = $input['category']['parent_id'];
            }
            $mtime = $this->phpdate->mtime();
            $param['code'] = 'C'.date('ymdHis',time()).substr($mtime,-4).rand(1000,9999);//毫秒时间戳加随机数
            $this->category_model->newData($param);
            redirect('admin/category/index');die;
        } catch (Exception $e) {
            $this->assign += $input['category'];
            //获取品牌列表
            if('yes' == $this->assign['is_admin']){
                $this->vendor('@.Brand_model');
                $brands = $this->brand_model->getAll();
                $this->assign['brand_opts'] = $brands;
            }
            if($input['category']['parent_id'] > 0){
                $info = $this->category_model->getOne(['id'=>$input['category']['parent_id']]);
                $this->assign['parent_id'] = $input['category']['parent_id'];
                $this->assign['parent_name'] = $info['name'];
                $this->assign['level'] = $info['level']+1;
                $this->assign['brand_id'] = $info['brand_id'];
            }else{
                $this->assign['parent_id'] = 0;
                $this->assign['parent_name'] = '';
                $this->assign['level'] = 1;
            }
            $this->assign['imageurl'] = $input['category']['upload_url'];
            $this->assign['error_code'] = $e->getMessage();
            $this->assign['view'] = 'admin/category/create';
            $this->load->view('admin/common/frame',$this->assign);
        }
    }
    /**
     * 创建页面
     * @author Toby.tu 2016-08-31
     */
    public function edit($id){
        $category = $this->category_model->getOne(['id'=>$id]);
        unset($category['status']);
        $this->assign += $category;
        $this->assign['id'] = $id;
        if($category['parent_id'] > 0){
            $info = $this->category_model->getOne(['id'=>$category['parent_id']]);
            $this->assign['parent_id'] = $category['parent_id'];
            $this->assign['parent_name'] = $info['name'];
            $this->assign['level'] = $info['level']+1;
            $this->assign['brand_id'] = $info['brand_id'];
        }else{
            $this->assign['parent_id'] = 0;
            $this->assign['parent_name'] = '';
            $this->assign['level'] = 1;
        }
        //获取品牌列表
        if('yes' == $this->assign['is_admin']){
            $this->vendor('@.Brand_model');
            $brands = $this->brand_model->getAll();
            $this->assign['brand_opts'] = $brands;
        }
        $this->assign['view'] = 'admin/category/edit';
        $this->load->view('admin/common/frame',$this->assign);
    }
    /**
     * 新增权限组
     * @author Toby.tu 2016-08-31
     */
    public function update($id){
        try {
            $input = $this->input->post();
            // dd($input);die;
            if(!isset($input['category'])){
                throw new Exception('参数不正确。');
            }
            if(empty($input['category']['name'])){
                throw new Exception('请输入分类名。');
            }
            $brand_id = 0;
            if(isset($input['category']['brand_id']) && $input['category']['brand_id'] > 0){
                $brand_id = $input['category']['brand_id'];
            }else if('yes' != $this->assign['is_admin']){//非管理员
                $brand_id = $this->permis_logic->getLoginUserInfo()['brand_id'];
            }
            $where = ['name'=>$input['category']['name']];
            if($brand_id > 0){
                $where['brand_id'] = $brand_id;
            }
			$where['delete_id'] = 0;
            $category = $this->category_model->getOne($where);
            if(!empty($category) && $id != $category['id']){
                throw new Exception('分类名已存在。');
            }
            $param = array();
            $param['name'] = $input['category']['name'];
            $param['imageurl'] = $input['category']['upload_url'];
            $param['update_time'] = $this->phpdate->time();
            $param['update_id'] = $this->permis_logic->getLoginUserInfo()['id'];
            $this->category_model->updateById($id,$param);
            redirect('admin/category/index');die;
        } catch (Exception $e) {
            $this->assign += $input['category'];
            $this->assign['id'] = $id;
            //获取品牌列表
            if('yes' == $this->assign['is_admin']){
                $this->vendor('@.Brand_model');
                $brands = $this->brand_model->getAll();
                $this->assign['brand_opts'] = $brands;
            }
            if($category['parent_id'] > 0){
                $info = $this->category_model->getOne(['id'=>$category['parent_id']]);
                $this->assign['parent_id'] = $category['parent_id'];
                $this->assign['parent_name'] = $info['name'];
                $this->assign['level'] = $info['level']+1;
                $this->assign['brand_id'] = $info['brand_id'];
            }else{
                $this->assign['parent_id'] = 0;
                $this->assign['parent_name'] = '';
                $this->assign['level'] = 1;
            }
            $this->assign['imageurl'] = $input['category']['upload_url'];
            $this->assign['error_code'] = $e->getMessage();
            $this->assign['view'] = 'admin/category/edit';
            $this->load->view('admin/common/frame',$this->assign);
        }
    }
    /**
     * 禁用启用
     * @author Toby.tu 2016-08-31
     */
    public function enable($id){
        try {
            $input = $this->input->get();
            if(!isset($input['status'])){
                throw new Exception('参数不正确。');
            }
            $param = array();
            $param['is_showimg'] = ($input['status']==1)?0:1;
            $param['update_id'] = $this->permis_logic->getLoginUserInfo()['id'];
            $param['update_time'] = $this->phpdate->time();
            $this->category_model->updateById($id,$param);
            redirect('admin/category/index');die;
        } catch (Exception $e) {
            redirect('admin/category/index');die;
        }
    }
    /**
     * 删除
     * @author Toby.tu 2016-08-31
     */
    public function destroy($id){
        if('yes' != $this->permis_logic->isAdmin()){
            die('不是管理员，不允许执行删除操作。');
        }
        $param = array();
        $current_id = $this->permis_logic->getLoginUserInfo()['id'];
        $param['delete_id'] = $current_id;
        $param['delete_time'] = $this->phpdate->time();
        $this->category_model->updateById($id,$param);
        //所有下级菜单都要同步删除
        $parentarr = $this->category_model->getCategoryByParent(['parent_id'=>$id]);
        if(!empty($parentarr)){//下级菜单不为空
            foreach ($parentarr as $parent) {
                $this->destroy($parent['id']);//递归删除
            }
        }
        redirect('admin/category/index');die;
    }
    public function upload(){
        $this->load->view('admin/category/upload',$this->assign);
    }
    /**
     * 上传地址
     * @author Toby.tu 2017-03-03
     */
    public function uploadfile(){
        $info = array();
        if (isset($_FILES['uploadFile'])){
            $namearr = explode('.', $_FILES['uploadFile']['name']);
            $mtime = $this->phpdate->mtime();
            $file = date('ymdHis',time()).substr($mtime,-4).rand(1000,9999).'.'.$namearr[1];//毫秒时间戳加随机数
            $path = 'upload/'.$this->phpdate->get('Y/m/d');
            $filepath = config_item('root_path').'/'.$path;
            $this->common->createdir($filepath);
            $config['upload_path']      = $filepath;
            $config['allowed_types']    = '*';
            $config['max_size']         = 1000000;
            $config['file_name']        = $file;

            $this->load->library('upload', $config);

            if ( ! $this->upload->do_upload('uploadFile')){
                echo json_encode(array('errorcode' => 1001 , 'errormsg' => $this->upload->display_errors()));
            }else{
                $info = $this->upload->data();
                $info['upload_path'] = $filepath;
                $info['upload_file'] = $file;
                $info['upload_name'] = $_FILES['uploadFile']['name'];
                $info['upload_type'] = $_FILES['uploadFile']['type'];
                $info['upload_size'] = $_FILES['uploadFile']['size'];
                $info['upload_url'] = base_url().$path.'/'.$file;
                $this->load->view('admin/category/upload',$info);
            }
        }
    }
    /**
     * 修改素材所属板块
     * @author Toby.tu 2017-03-06
     */
    public function updateGroup(){
        try {
            $input = $this->input->post();
            if(!isset($input['brandinfo_id']) || !isset($input['category_id'])){
                throw new Exception('参数不正确。');
            }
            $param = array();
            $param['brandinfo_id'] = $input['brandinfo_id'];
            $param['update_id'] = $this->permis_logic->getLoginUserInfo()['id'];
            $param['update_time'] = $this->phpdate->time();
            $category_id_arr = explode(',',$input['category_id']);
            $this->category_model->updateInId($category_id_arr,$param);
            $this->ajaxReturn('SUCCESS');
        } catch (Exception $e) {
            $this->ajaxReturn($e->getMessage(),$e->getCode());
        }
    }
    /**
     * 显示
     * @author Toby.tu 2017-03-06
     */
    public function show($id=0){
        if(!$id) die('参数错误');
    }
    /**
     * 获取对应的商品分类
     * @author Toby.tu 2017-03-06
     */
    public function getCategoryByParent(){
        try {
            $input = $this->input->post();
            if(empty($input['ajax']) || !isset($input['parent_id'])){
                throw new Exception('参数不正确。');
            }
            $brand_id = 0;
            if(isset($input['brand_id']) && $input['brand_id'] > 0){
                $brand_id = $input['brand_id'];
            }else if('yes' != $this->assign['is_admin']){//非管理员
                $brand_id = $this->permis_logic->getLoginUserInfo()['brand_id'];
            }
            if(empty($brand_id)){
                throw new Exception('没有相关品牌id。');
            }
            $param = array();
            $param['parent_id'] = $input['parent_id'];
            $param['brand_id'] = $brand_id;
            $category = $this->category_model->getCategoryByParent($param);
            $this->ajaxReturn($category);
        } catch (Exception $e) {
            $this->ajaxReturn($e->getMessage(),$e->getCode());
        }

    }
}
